﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QAbstractSocket>
#include <QHostAddress>
#include <QNetworkProxy>
#pragma execution_character_set("utf-8")

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_tcpSocket = new QTcpSocket(this);
    connect(m_tcpSocket,&QTcpSocket::connected,[=](){
        qDebug() << "connect  connect";
    });

    connect(m_tcpSocket,&QTcpSocket::readyRead,this,&MainWindow::onReadMessage);

    ui->pB_connect->setEnabled(true);
    ui->pB_disconnect->setEnabled(false);
    ui->pB_send->setEnabled(false);
}

MainWindow::~MainWindow()
{
    delete ui;

}

void MainWindow::onReadMessage()
{
    QByteArray bt;
    bt.resize(m_tcpSocket->bytesAvailable());
    m_tcpSocket->read(bt.data(),bt.size()); //使用read接收数据
    mInsertTextBycolor(Qt::black,bt);
}

void MainWindow::onDisplayError(QAbstractSocket::SocketError e)
{
    qDebug()<<"SocketError:"<<e<<endl
           <<m_tcpSocket->errorString();
}


void MainWindow::on_pB_connect_clicked()
{

    //连接服务端
    QString IP = ui->lE_ip->text();
    quint16 Port = ui->lE_port->text().toInt();
    m_tcpSocket->connectToHost(IP,Port);

    timer = new QTimer(this);
    timer->setSingleShot(true);
    timer->setInterval(5000);
    connect(m_tcpSocket,&QTcpSocket::connected,this,&MainWindow::onConnected);
    connect(m_tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(onError(QAbstractSocket::SocketError)));
    connect(timer,SIGNAL(timeout()),this,SLOT(onTimeout()));
    timer->start();
    this->setEnabled(false);
}

void MainWindow::on_pB_send_clicked()
{
    QByteArray array = ui->tE_Send->toPlainText().toUtf8();
    m_tcpSocket->write(array);
//    m_tcpSocket->flush();//清空缓冲区
    mInsertTextBycolor(Qt::red,array);

}

void MainWindow::on_pB_disconnect_clicked()
{
    m_tcpSocket->close();
    ui->tE_rec->insertPlainText("断开连接");
    ui->pB_connect->setEnabled(true);
    ui->pB_disconnect->setEnabled(false);
    ui->pB_send->setEnabled(false);


}

void MainWindow::onConnected()
{
    ui->tE_rec->insertPlainText("连接成功");
    ui->pB_connect->setEnabled(false);
    ui->pB_disconnect->setEnabled(true);
    ui->pB_send->setEnabled(true);
    this->setEnabled(true);
}

void MainWindow::onError(QAbstractSocket::SocketError socketError)
{
    ui->tE_rec->append(m_tcpSocket->errorString());
    this->setEnabled(true);
    on_pB_disconnect_clicked();
}

void MainWindow::onTimeout()
{
    ui->tE_rec->append(m_tcpSocket->errorString());
    this->setEnabled(true);
    m_tcpSocket->abort();

}

void MainWindow::mInsertTextBycolor(Qt::GlobalColor color, QString str)
{
    QTextCursor textCursor = ui->tE_rec->textCursor();
    QTextCharFormat charFormat;
    charFormat.setForeground(QBrush(QColor(color)));
    textCursor.setCharFormat(charFormat);
    textCursor.insertText(str);
    ui->tE_rec->moveCursor(QTextCursor::End);
    ui->tE_rec->ensureCursorVisible();
}
